<template>
    <div class="table-box">
        <div class="table-search">
            <el-form :inline="true" :model="form">
                <el-form-item label="商品名称">
                    <el-input v-model="form.name" placeholder="商品名称" />
                </el-form-item>
                <el-form-item label="项目">
                    <el-select v-model="form.project" placeholder="项目">
                        <el-option label="mobybox" value="mobybox" />
                        <el-option label="slotsgame" value="slotsgame" />
                    </el-select>
                 </el-form-item>
                <el-form-item label="状态">
                    <el-select clearable v-model="form.status" placeholder="状态">
                        <el-option label="进行中" :value="1" />
                        <el-option label="未开始" :value="2" />
                        <el-option label="已结束" :value="3" />
                    </el-select>
                 </el-form-item>
                 <el-form-item clearable label="是否隐藏">
                    <el-select v-model="form.is_hide" placeholder="是否隐藏">
                        <el-option label="是" :value="1" />
                        <el-option label="否" :value="0" />
                    </el-select>
                 </el-form-item>
                 <el-form-item clearable label="开始时间">
                    <el-date-picker
                      v-model="form.startData"
                      type="datetimerange"
                      range-separator="至"
                      start-placeholder="开始时间"
                      end-placeholder="开始时间" :default-time="pickerDefaultTime"
                    />
                  </el-form-item>
                  <el-form-item clearable label="结束时间">
                    <el-date-picker
                      v-model="form.endData"
                      type="datetimerange"
                      range-separator="至"
                      start-placeholder="结束时间"
                      end-placeholder="结束时间" :default-time="pickerDefaultTime"
                    />
                  </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onQuery">查询</el-button>
                    <el-button @click="onReset">重置</el-button>
                    <el-button type="primary" plain @click="onAdd">新增</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="card content-box">
            <div class="table">
                <el-table ref="multipleTableRef" @selection-change="handleSelectionChange" :data="tableData" border v-loading="loading">
                    <el-table-column type="selection" width="45" />
                    <el-table-column prop="id" label="ID" align="center" />
                    <el-table-column prop="project" label="项目名称" align="center" width="120"/>
                    <el-table-column prop="name" label="商品名称" align="center"  />
                    <el-table-column prop="category" label="类型" align="center" />
                    <el-table-column label="缩略图" align="center" width="100">
                        <template #default="scope">
                            <el-image style="width: 70px; height: 70px" :src="scope.row.thumb_show" alt="" fit="fill"
                                :preview-src-list="[scope.row.thumb_show]" :preview-teleported="true"></el-image>
                        </template>
                    </el-table-column>
                    <el-table-column prop="unit" label="单位" align="center" />
                    <el-table-column prop="price" label="单价" align="center" />
                    <el-table-column prop="total_price" label="商品总价" align="center" />
                    <el-table-column prop="buy_price" label="已购买总价" align="center" />
                    <el-table-column prop="buy_count" label="已购买次数" align="center" />
                    <el-table-column label="详情图" align="center" width="100">
                        <template #default="scope">
                            <el-image style="width: 70px; height: 70px" :src="scope.row.image_show" alt="" fit="fill"
                                :preview-src-list="[scope.row.image_show]" :preview-teleported="true"></el-image>
                        </template>
                    </el-table-column>
                    <el-table-column prop="is_hide" label="是否隐藏" align="center" :formatter="formatter" />
                    <el-table-column prop="start_time" label="开始时间" align="center" :formatter="formatterTime" width="180" />
                    <el-table-column prop="end_time" label="结束时间" align="center" :formatter="formatterTime" width="180" />
                    <el-table-column prop="win_number" label="中奖号码" align="center"  />
                    <el-table-column prop="win_uid" label="中奖用户UID" align="center"  />
                    <el-table-column prop="rank" label="排序" align="center" />
                    <el-table-column prop="createtime" label="添加时间" align="center" :formatter="formatterTime" width="180" />
                    <el-table-column label="操作" align="center" width="180" fixed="right">
                        <template #default="scope">
                            <el-button type="primary" plain
                                @click="handleOperate(scope.$index, scope.row, 'edit')">编辑</el-button>
                            <el-button type="danger"  @click="handleOperate(scope.$index, scope.row, 'copy')">复制</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-row>
                   <el-col :span="8" style="padding-top:20px;">
                   <el-button type="primary" @click="batchOperate('copy')">批量复制</el-button>
                   <el-button type="success" @click="batchOperate('online')">批量上架</el-button>
                   <el-button type="warning" @click="clearAllSelection()">清除选择</el-button>
                   </el-col>
                   <el-col :span="16">
                   <div class="table-pagination">
                   <el-pagination :current-page="pageable.pageNum" :page-size="pageable.pageSize"
                        :page-sizes="[10, 25, 50, 100]" :background="true" layout="total, sizes, prev, pager, next, jumper"
                        :total="pageable.total" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"></el-pagination>
                        </div>
                   </el-col>
                </el-row>
            </div>
        </div>
        <DialogForm @cancel="cancel" @closeDialog="closeDialog" @submitForm="submit"
            @handleUploaderThumbSuccess="handleUploader" @handleUploaderImgRequest="handleUploader"
            :dialogFormVisible="dialogVisible" :dialogForm="dialogForm" :btnLoading="btnLoading" />
    </div>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import {
    formatterTime,
    formatter,
    formatDates,
    timestamp, pickerDefaultTime
} from "@/utils/utils";
import {
    activityDuobaoProductsApi,
    activityProductsApi,
    activityProductsBatchOperateApi,
} from "@/api/moby/activity/activity";
import DialogForm from "./components/dialogForm.vue";
const tableData = ref([]);
const loading = ref(false);
const dialogVisible = ref(false);
const btnLoading = ref(false);
const multipleTableRef = ref();
const multipleProducts = reactive([]);
const formData = {
    name: "",
    project:"mobybox",
    status:"",
    startData:[],
    endData:[],
    is_hide:""
};
const form = reactive({ ...formData });
const dialogFormData = {
    // thumb_show: "",
    product_id: "",
    name: "",
    category: "home",
    content: "",
    image: "",
    unit: "diamond",
    price: "",
    total_price: "",
    start_time: "",
    end_time: "",
    is_hide: "",
    // is_hide: "",
    thumb: "",
    times: "",
    image_show: "",
    project: "mobybox",
};
const dialogForm = reactive({ ...dialogFormData });
const pageable = reactive({
    pageNum: 1,
    pageSize: 10,
    total: 0,
});
// 参数
const param = () => {
    return {
        page: pageable.pageNum,
        pagesize: pageable.pageSize,
        name: form.name,
        project:form.project,
        status:form.status,
        start_start:form.startData[0] ? timestamp(form.startData[0].valueOf()) : "",
        start_end:form.startData[1] ? timestamp(form.startData[1].valueOf()) : "",
        end_start:form.endData[0] ? timestamp(form.endData[0].valueOf()) : "",
        end_end:form.endData[1] ? timestamp(form.endData[1].valueOf()) : "",
        is_hide:form.is_hide
    };
};
// 选中/取消
const handleSelectionChange = (val) => {
    if (val.length != 0) {
        multipleProducts.value = [];
        val.forEach((element) => {
            multipleProducts.value.push(element.id);
        });
    } else {
        multipleProducts.value = [];
    }
//    console.log(multipleProducts.value);
};
// 清除选中
const clearAllSelection = () => {
    multipleTableRef.value?.clearSelection();
    multipleProducts.value = [];
}
// 获取表格数据
const getTbaleData = async () => {
    loading.value = true;

    try {
        const res = await activityDuobaoProductsApi(param());
        loading.value = false;
        tableData.value = res.data.results;
        pageable.total = res.data.count;
    } catch (error) {
        loading.value = false;
    }
};
// 重置
const onReset = () => {
    Object.assign(form, formData);
    getTbaleData();
};
// 查询
const onQuery = async () => {
    getTbaleData();
};
//新增
const onAdd = () => {
    dialogVisible.value = true;
};
const batchOperate = async (type) => {
    // 批量复制、上架
//    console.log(multipleProducts.value, type)
    if (multipleProducts.value.length == 0) {
        ElMessage.error("未选择商品");
        return false;
    }
    try {
        const res = await activityProductsBatchOperateApi({product_ids: multipleProducts.value, op_type: type });
        getTbaleData();
        ElMessage.success(res.message)
    } catch (error) {
        ElMessage.error("操作失败");
        return false;
    }
};
const handleOperate = async (index, row, type) => {
    // 编辑
    if (type === "edit") {
        Object.assign(dialogForm, {
            ...row,
            product_id: row.id,
            times: [formatDates(row.start_time), formatDates(row.end_time)],
        });
        dialogVisible.value = true;
    }
    if (type === "copy") {
        try {
            const res = await activityProductsBatchOperateApi({product_ids: [row.id], op_type: 'copy' });
            getTbaleData();
            ElMessage.success(res.message);
        } catch (error) {
            ElMessage.error("操作失败");
            return false;
        }
    }
};
//关闭弹窗
const closeDialog = () => {
    dialogVisible.value = false;
    Object.assign(dialogForm, dialogFormData);
};

// 取消
const cancel = () => {
    dialogVisible.value = false;
    Object.assign(dialogForm, dialogFormData);
};
// 提交
const submit = async (param) => {
    delete param.id;
    delete param.createtime;
    delete param.updatetime;
    param.thumb_show = dialogForm.thumb_show;
    param.thumb = dialogForm.thumb;
    try {
        btnLoading.value = true;
        const res = await activityProductsApi(param);

        ElMessage({
            message: res.message,
            type: "success",
        });

        dialogVisible.value = false;
        btnLoading.value = false;
        getTbaleData();
    } catch (error) {
        btnLoading.value = false;
        dialogVisible.value = false;
        return false;
    }
};
// //上传图标
const handleUploader = (res,name,src ) => {
    if (res.code === 0) {
        ElMessage({
            message: "图片上传成功",
            type: "success",
        });
        dialogForm[`${src}`] = res.data.pic_url || "";
        dialogForm[`${name}`] = res.data.name || "";
    }
};
// 条数
const handleSizeChange = (number) => {
    pageable.pageSize = number;
    getTbaleData();
};
// 页码
const handleCurrentChange = (number) => {
    pageable.pageNum = number;
    getTbaleData();
};
onMounted(() => {
    getTbaleData();
});
</script>
